package com.example.userspringboot.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.example.userspringboot.entity.User;
import com.example.userspringboot.exception.CustomerException;
import com.example.userspringboot.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    @Resource
    UserMapper userMapper;

    public User login(User user) {
        // 查询用户名是否存在
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (dbUser == null){
            throw new CustomerException("用户名不存在");
        }
        // 密码是否正确
        if (!dbUser.getPassword().equals(DigestUtil.md5Hex(user.getPassword()))){
            throw new CustomerException("账号或密码错误");
        }
        return dbUser;
    }

    public void register(User user) {
        this.add(user);
    }

    public void add(User user) {
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (dbUser != null){
            throw new CustomerException("该账号已存在");
        }
        // 默认密码
        if (StrUtil.isBlank(user.getPassword())){
            user.setPassword(DigestUtil.md5Hex("123"));
        } else{
            user.setPassword(DigestUtil.md5Hex(user.getPassword()));
        }
        if (StrUtil.isBlank(user.getName())){
            user.setName(System.currentTimeMillis() + "_" + "user");
        }
        user.setRole("USER");
        userMapper.insert(user);
    }

    public void update(User user) {
        userMapper.updateById(user);
    }

    public void updatePassword(User user) {
        // 先判断一下用户输入的新密码和确认密码是否一致
        if (!user.getNewPassword().equals(user.getConfirmPassword())){
            throw new CustomerException("500","新密码和确认密码不一致");
        }
        // 密码正确，修改密码
        User dbUser = userMapper.selectById(user.getId().toString());
        if (!dbUser.getPassword().equals(DigestUtil.md5Hex(user.getOriginalPassword()))){
            throw new CustomerException("500","原密码输入错误");
        }
        user.setPassword(DigestUtil.md5Hex(user.getNewPassword()));
        userMapper.updateById(user);
    }
}
